import {
	productionPrdMonthReportCreate, productionPrdMonthReportFixDate,
	productionPrdMonthReportGet,
	productionPrdMonthReportGetDate,
	productionPrdMonthReportHistoryGet,
	productionPrdMonthReportHistoryPage,
	productionPrdMonthReportHistorySetMaster,
	productionPrdMonthReportUpdate,
	productionPrdMonthReportUpdateStatus
} from '../../../../../api/production/monthEndReport';
import { formatDate, tipsBar } from '../../../../../utils/jk/jk-tool';
import { openStateList, reportStateList } from '../../../../../utils/jk/status-option-list';
import XEUtils from 'xe-utils';
import { workforcemanagementScheduleList } from '../../../../../api/schedule/scheduling';
import { mathJsAdd, mathJsDiv, mathJsMul, mathJsSub } from '../../../../../utils/jk/jk-cals';
import handlerCache from '../../../../../mixins/handler-cache';
let _this = null;
export default {
	mixins: [handlerCache],
	components: {},
	props: {
		pageType: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			prefix: 'production:prdReport',
			apiItem: {
				'save': productionPrdMonthReportCreate,
				'update': productionPrdMonthReportUpdate
			},
			productList: [],
			tableLoading: false,
			reportStateList: reportStateList,
			openStateList: openStateList,
			dataId: null,
			showLoading: false,
			saveBtnLoading: false,
			releaseBtnLoading: false,
			workshopList: [],
			processList: [],
			saveDialogState: false,
			scheduleShiftList: [],
			historyData: [],
			ruleForm: {
				'code': '',
				'type': 2,
				'generateType': 1,
				'belongDate': '',
				'shiftWeightQty': 0,
				'historyCount': 0,
				'prdReportMachineList': [],
				'processCode': '',
				'processId': null,
				'processName': '',
				'scheduleShiftId': null,
				'shiftElectricEnergy': null,
				'shiftId': null,
				'shiftName': '',
				'shiftOutput': null,
				'shiftQty': null,
				'wasteRate': null,
				'workshopId': null,
				'workshopName': '',
				'remark': ''
			},
			rules: {
				processId: [{ required: true, trigger: 'change' }],
				belongDate: [{ required: true, trigger: 'change' }],
				scheduleShiftId: [{ required: true, trigger: 'change' }],
				workshopId: [{ required: true, trigger: 'change' }]
			},
			unReleaseBtnLoading: false
		};
	},
	methods: {
		onRawOutput(e, scope) {
			if (this.ruleForm.processCode && ['BT'].includes(this.ruleForm.processCode.toUpperCase())) {
				let val = 0;
				if (scope.row.gramWeight && scope.row.meters) {
					val = mathJsDiv(e, scope.row.meters);
					val = mathJsMul(val, scope.row.gramWeight);
					val = mathJsDiv(val, 1000).toFixed(2);
					val = Number(val);
				}
				this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'differenceValue', e);
				this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'shiftQty', val);
			}
		},
		onRefreshMachineItemBtn(scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'loading', true);
			const params = {
				'belongDate': this.ruleForm.belongDate,
				'fixData': scope.row,
				'processCode': this.ruleForm.processCode,
				'processId': this.ruleForm.processId,
				'scheduleId': this.ruleForm.scheduleId,
				'scheduleShiftId': this.ruleForm.scheduleShiftId,
				'shiftId': this.ruleForm.shiftId,
				'workshopId': this.ruleForm.workshopId
			};
			productionPrdMonthReportFixDate(params).then(res => {
				this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'loading', false);
				if (res.data.status === 200) {
					const item = JSON.parse(JSON.stringify(res.data.res));
					item.loading = false;
					this.$set(this.ruleForm.prdReportMachineList, scope.rowIndex, item);
				}
			});
		},
		onUnReleaseBtn() {
			this.unReleaseBtnLoading = true;
			productionPrdMonthReportUpdateStatus({
				id: this.ruleForm.id
			}).then(res => {
				this.unReleaseBtnLoading = false;
				if (res.data.status === 200) {
					this.$tipsBar(this, 'save');
					this.$store.dispatch('tagsView/delView', { path: this.$route.path });
					this.$toOtherRouter({
						name: `editProductionReport`,
						query: {
							id: this.ruleForm.id,
							processCode: this.$route.query.processCode
						}
					});
				}
			});
		},
		clearCacheMethod() {
			Object.assign(this.$data, this.$options.data());
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
				this.getDependentData();
			});
		},
		onUseHistory(row) {
			this.$confirm(`确定将该版本(${row.version}.0)设置为主版本吗?`, { type: 'warning' }).then(() => {
				return productionPrdMonthReportHistorySetMaster({}, { id: row.id }).then(res => {
					if (res.data.status === 200) {
						this.$toOtherRouter({
							name: 'detailXsReport',
							query: {
								id: res.data.res
							}
						});
						this.getDependentData();
					}
				});
			});
		},
		mergeColMethod({ row, _rowIndex, column, visibleData }) {
			const prevRow = visibleData[_rowIndex - 1];
			let nextRow = visibleData[_rowIndex + 1];
			if (column.property === 'machineName') {
				if (prevRow && prevRow.machineName && prevRow.machineName === row.machineName) {
					return { rowspan: 0, colspan: 0 };
				} else {
					let countRowspan = 1;
					while (nextRow && nextRow.machineName && nextRow.machineName === row.machineName) {
						nextRow = visibleData[++countRowspan + _rowIndex];
					}
					if (countRowspan > 1) {
						return { rowspan: countRowspan, colspan: 1 };
					}
				}
			} else {
				// 针对并线合并-如：并线4-1右、并线4-1左
			    if (['BX'].includes(this.ruleForm.processCode.toUpperCase())) {
					if (column.property === 'startElectricEnergy') {
						if (prevRow && prevRow.machineName && prevRow.machineName && row.machineName && prevRow.machineName.substring(0, prevRow.machineName.length - 1) === row.machineName.substring(0, row.machineName.length - 1)) {
							return { rowspan: 0, colspan: 0 };
						} else {
							let countRowspan = 1;
							while (nextRow && nextRow.machineName && row.machineName && nextRow.machineName.substring(0, nextRow.machineName.length - 1) === row.machineName.substring(0, row.machineName.length - 1)) {
								nextRow = visibleData[++countRowspan + _rowIndex];
							}
							if (countRowspan > 1) {
								return { rowspan: countRowspan, colspan: 1 };
							}
						}
					} else if (column.property === 'endElectricEnergy') {
						if (prevRow && prevRow.machineName && prevRow.machineName && row.machineName && prevRow.machineName.substring(0, prevRow.machineName.length - 1) === row.machineName.substring(0, row.machineName.length - 1)) {
							return { rowspan: 0, colspan: 0 };
						} else {
							let countRowspan = 1;
							while (nextRow && nextRow.machineName && row.machineName && nextRow.machineName.substring(0, nextRow.machineName.length - 1) === row.machineName.substring(0, row.machineName.length - 1)) {
								nextRow = visibleData[++countRowspan + _rowIndex];
							}
							if (countRowspan > 1) {
								return { rowspan: countRowspan, colspan: 1 };
							}
						}
					} else if (column.property === 'shiftElectricEnergy') {
						if (prevRow && prevRow.machineName && prevRow.machineName && row.machineName && prevRow.machineName.substring(0, prevRow.machineName.length - 1) === row.machineName.substring(0, row.machineName.length - 1)) {
							return { rowspan: 0, colspan: 0 };
						} else {
							let countRowspan = 1;
							while (nextRow && nextRow.machineName && row.machineName && nextRow.machineName.substring(0, nextRow.machineName.length - 1) === row.machineName.substring(0, row.machineName.length - 1)) {
								nextRow = visibleData[++countRowspan + _rowIndex];
							}
							if (countRowspan > 1) {
								return { rowspan: countRowspan, colspan: 1 };
							}
						}
					}
				}
			}
		},
		// 输入,开始能耗表数
		onStartElectricEnergy(e, scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'startElectricEnergy', e);
			// 针对并线合并-如：并线4-1右、并线4-1左, 能耗只算其中一个机台，其余赋值为0
			if (['BX'].includes(this.ruleForm.processCode.toUpperCase())) {
				this.ruleForm.prdReportMachineList.forEach(x => {
					if (x.machineId !== scope.row.machineId) {
						if (x.machineName && x.machineName.substring(0, x.machineName.length - 1) === scope.row.machineName.substring(0, scope.row.machineName.length - 1)) {
							this.$set(x, 'startElectricEnergy', 0);
							this.$set(x, 'shiftElectricEnergy', 0);
						}
					}
				});
			}
			this.calMachineItemVal(scope);
		},
		// 输入,结束能耗表数
		onEndElectricEnergy(e, scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'endElectricEnergy', e);
			// 针对并线合并-如：并线4-1右、并线4-1左, 能耗只算其中一个机台，其余赋值为0
			if (['BX'].includes(this.ruleForm.processCode.toUpperCase())) {
				this.ruleForm.prdReportMachineList.forEach(x => {
					if (x.machineId !== scope.row.machineId) {
						if (x.machineName && x.machineName.substring(0, x.machineName.length - 1) === scope.row.machineName.substring(0, scope.row.machineName.length - 1)) {
							this.$set(x, 'endElectricEnergy', 0);
							this.$set(x, 'shiftElectricEnergy', 0);
						}
					}
				});
			}
			this.calMachineItemVal(scope);
		},
		calTotal() {
			let valM = 0;
			let valKg = 0;
			let valKgWeight = 0;
			let valEn = 0;
			this.ruleForm && this.ruleForm.prdReportMachineList ? this.ruleForm.prdReportMachineList.forEach(x => {
				valM = mathJsAdd(x.shiftOutput || 0, valM);
				valKg = mathJsAdd(x.shiftQty || 0, valKg);
				valKgWeight = mathJsAdd(x.shiftWeightQty || 0, valKgWeight);
				valEn = mathJsAdd(x.shiftElectricEnergy || 0, valEn);
			}) : [];
			this.$set(this.ruleForm, 'shiftOutput', valM);
			this.$set(this.ruleForm, 'shiftQty', valKg);
			this.$set(this.ruleForm, 'shiftWeightQty', valKgWeight);
			this.$set(this.ruleForm, 'shiftElectricEnergy', valEn);
		},
		// 输入,开始产量表数
		onStartOutput(e, scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'startOutput', e);
			this.calMachineItemVal(scope);
		},
		// 输入,当班能耗表数
		onShiftElectricEnergy(e, scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'shiftElectricEnergy', e);
			this.calMachineItemVal(scope);
		},
		// 输入,结束产量表数
		onEndOutput(e, scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'endOutput', e);
			this.calMachineItemVal(scope);
		},
		onOutputRatio(e, scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'outputRatio', e);
			this.calMachineItemVal(scope);
		},
		onOpenSpinCount(e, scope) {
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'openSpinCount', e);
			this.calMachineItemVal(scope);
		},
		calMachineItemVal(scope) {
			/** 第一,计算当班产量(M) */
			// 当班产量表量(M) = 当班产量表量 = (结束产量表数 - 开始产量表数) * 系数
			if (scope.row.startOutput < scope.row.endOutput) {
				let val = mathJsSub((scope.row.endOutput || 0), (scope.row.startOutput || 0));
				val = mathJsMul(val, scope.row.outputRatio);
				val = parseFloat(val.toFixed(2));
				// 是单锭时需 * 开台锭数
				if (scope.row.ifSpinOutput) {
					val = mathJsMul(val, scope.row.openSpinCount || 0);
				}
				this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'differenceValue', val);
				this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'shiftOutput', val);
			} else {
				this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'differenceValue', 0);
				this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'shiftOutput', 0);
			}
			// 当班产量表量KG = 当班产量表量 / 米长 * 克重 / 1000
			let valKg1 = 0;
			if (scope.row.meters) {
				valKg1 = mathJsDiv(scope.row.differenceValue, scope.row.meters);
				valKg1 = mathJsMul(valKg1, scope.row.gramWeight || 0);
				valKg1 = mathJsDiv(valKg1, 1000);
				valKg1 = parseFloat(valKg1.toFixed(2));

				// meters表示每米的公斤数 = 克重 / 米长 * 1000
				// valKg1 = mathJsMul(scope.row.differenceValue, scope.row.meters || 0);
				// valKg1 = parseFloat(valKg1.toFixed(2));
			}
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'shiftQty', valKg1);

			/** 第二,计算当班能耗表数 */
			// 当班能耗表数 = 结束能耗表数 - 开始能耗表数
			let energyVal = mathJsSub(scope.row.endElectricEnergy, scope.row.startElectricEnergy);
			energyVal = parseFloat(energyVal.toFixed(2));
			this.$set(this.ruleForm.prdReportMachineList[scope.rowIndex], 'shiftElectricEnergy', energyVal);
		},
		footerMethod({ columns, data }) {
			const keys = ['shiftWeightQty', 'shiftQty', 'shiftOutput', 'shiftElectricEnergy', 'differenceValue', 'rawOutput'];
			return [
				columns.map((column, columnIndex) => {
					if (columnIndex === 0) {
						return '合计';
					}
					if (keys.includes(column.field)) {
						return XEUtils.sum(data, column.field);
					}
					return null;
				})
			];
		},
		onWorkshopChange() {
			this.$set(this.ruleForm, 'prdReportMachineList', []);
			this.$set(this.ruleForm, 'scheduleShiftId', null);
			this.$set(this.ruleForm, 'shiftId', null);
			this.$set(this.ruleForm, 'shiftName', null);
			this.scheduleShiftList = [];
			this.getDateScheduleShiftOptionRequest();
		},
		onProcessChange(e) {
			const item = this.processList.find(x => x.id === e) || {};
			this.$set(this.ruleForm, 'processCode', item.code);
			this.$set(this.ruleForm, 'processName', item.name);
			this.$set(this.ruleForm, 'prdReportMachineList', []);
			this.getOpenMachineListRequest();
		},
		onJumpList() {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toMainRouter({
				name: `ProductionReport`
			});
		},
		onJump(id) {
			this.$store.dispatch('tagsView/delView', { path: this.$route.path });
			this.$toMainRouter({
				name: `editProductionReport`,
				query: {
					id: id
				}
			});
		},
		setDependentDataOfForm() {
			const params = JSON.parse(JSON.stringify(this.ruleForm));
			params.prdReportMachineList.forEach(x => {
				delete x.loading;
			});

			const workshopItem = this.workshopList.find(x => x.id === params.workshopId) || {};
			params.workshopCode = workshopItem.code;
			params.workshopName = workshopItem.name;

			const processItem = this.processList.find(x => x.id === params.processId) || {};
			params.processCode = processItem.code;
			params.processName = processItem.name;

			if (!this.dataId) {
				const shiftItem = this.scheduleShiftList.find(x => x.id === params.scheduleShiftId) || {};
				params.shiftId = shiftItem.shiftId;
				params.shiftName = shiftItem.shiftName;
			}
			return params;
		},
		onConfirmBtn(from = 'save') {
			this.$refs['ruleForm'].validate(valid => {
				if (valid) {
					// 核实
					if (from === 'release') {
						this.releaseRequest();
					} else {
						this.createAndUpdateRequest();
					}
				} else {
					this.$tipsBar(this, 'validator');
				}
			});
		},
		createAndUpdateRequest() {
			this.saveBtnLoading = true;
			// 新增
			if (!this.dataId) {
				this.ruleForm.id = null;
				productionPrdMonthReportCreate(this.setDependentDataOfForm()).then(res => {
					this.saveBtnLoading = false;
					if (res.data.status === 200) {
						this.$tipsBar(this, 'save');
						this.onJump(res.data.res);
					}
				});
				return;
			}
			// 编辑
			productionPrdMonthReportUpdate(this.setDependentDataOfForm()).then(res => {
				this.saveBtnLoading = false;
				if (res.data.status === 200) {
					this.$tipsBar(this, 'save');
					this.getDependentData();
				}
			});
		},
		releaseRequest() {
			this.releaseBtnLoading = true;
			// 先保存再核实
			productionPrdMonthReportUpdate(this.setDependentDataOfForm()).then(res => {
				if (res.data.status === 200) {
					productionPrdMonthReportUpdateStatus({
						id: this.ruleForm.id
					}).then(res => {
						this.releaseBtnLoading = false;
						if (res.data.status === 200) {
							this.$tipsBar(this, 'save');
							this.$store.dispatch('tagsView/delView', { path: this.$route.path });
							this.$toOtherRouter({
								name: `detailProductionReport`,
								query: {
									id: this.ruleForm.id,
									processCode: this.$route.query.processCode || ''
								}
							});
						}
					});
				} else {
					this.getDependentData();
					this.releaseBtnLoading = false;
				}
			});
		},
		onVisibleChange(e) {
			this.$emit('on-visible-change', e);
			if (!e) {
				Object.assign(this.$data, this.$options.data());
				this.$nextTick(() => {
					this.$refs.ruleForm.resetFields();
				});
			}
		},
		getProductList() {
			const productConf = {};
			if (this.ruleForm.prdReportMachineList) {
				this.ruleForm.prdReportMachineList.forEach(x => {
					if (productConf[x.batchCode]) {
						productConf[x.batchCode].shiftQty = mathJsAdd(x.shiftQty, productConf[x.batchCode].shiftQty || 0);
						productConf[x.batchCode].differenceValue = mathJsAdd(x.differenceValue, productConf[x.batchCode].differenceValue || 0);
					} else {
						productConf[x.batchCode] = {
							batchCode: x.batchCode,
							productName: x.productName,
							differenceValue: x.differenceValue,
							shiftQty: x.shiftQty
						};
					}
				});
			}
			this.productList = [];
			for (const key in productConf) {
				this.productList.push(productConf[key]);
			}
		},
		getDetailRequest() {
			let api = null;
			if (this.$route.query.formPage && this.$route.query.formPage === 'history') {
				api = productionPrdMonthReportHistoryGet;
			} else {
				api = productionPrdMonthReportGet;
			}
			return api({ id: this.$route.query.id }).then(res => {
				this.showLoading = false;
				if (res.data.status === 200) {
					const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : {};
					resData.prdReportMachineList = resData.prdReportMachineList ? resData.prdReportMachineList.map(x => {
						x.loading = false;
						return x;
					}) : [];
					const arr = this.clearBxEnergy(resData.prdReportMachineList || []);
					resData.prdReportMachineList = arr;
					this.ruleForm = resData;
					this.getProductList();
					this.calTotal();
				}
			});
		},
		onSeeHistory(row) {
			this.$toOtherRouter({
				name: 'detailXsReport',
				query: {
					id: row.id,
					formPage: 'history'
				}
			});
			this.getDependentData();
		},
		onScheduleShiftChange(e) {
			let item = {};
			if (e) {
				item = this.scheduleShiftList.find(x => x.id === e);
			} else {
				item = {
					id: null,
					shiftId: null,
					shiftName: null,
					scheduleId: null
				};
			}
			this.$set(this.ruleForm, 'scheduleId', item.scheduleId);
			this.$set(this.ruleForm, 'scheduleShiftId', item.id);
			this.$set(this.ruleForm, 'shiftId', item.shiftId);
			this.$set(this.ruleForm, 'shiftName', item.shiftName);
			this.getOpenMachineListRequest();
		},
		getOpenMachineListRequest() {
			if (this.ruleForm.workshopId && this.ruleForm.processId && this.ruleForm.belongDate && this.ruleForm.scheduleShiftId) {
				this.tableLoading = true;
				productionPrdMonthReportGetDate({
					workshopId: this.ruleForm.workshopId,
					processId: this.ruleForm.processId,
					shiftId: this.ruleForm.shiftId,
					scheduleShiftId: this.ruleForm.scheduleShiftId,
					belongDate: this.ruleForm.belongDate
				}).then(res => {
					this.tableLoading = false;
					if (res.data.status === 200) {
						const arr = this.clearBxEnergy(res.data.res || []);
						this.$set(this.ruleForm, 'prdReportMachineList', arr);
						this.calTotal();
					}
				});
			}
		},
		// 清除并线的能耗（左、右，能耗只计算其中一个）
		clearBxEnergy(arr) {
			const conf = {};
			arr.forEach(x => {
				if (['BX'].includes(this.ruleForm.processCode.toUpperCase())) {
					if (x.machineName && !conf[x.machineName.substring(0, x.machineName.length - 1)]) {
						conf[x.machineName.substring(0, x.machineName.length - 1)] = x.machineName.substring(0, x.machineName.length - 1);
					} else {
						x.startElectricEnergy = 0;
						x.endElectricEnergy = 0;
						x.shiftElectricEnergy = 0;
					}
				}
			});
			return arr;
		},
		getDateScheduleShiftOptionRequest() {
			if (this.ruleForm.workshopId && this.ruleForm.belongDate) {
				return workforcemanagementScheduleList({
					belongDate: [this.ruleForm.belongDate, this.ruleForm.belongDate],
					workshopId: this.ruleForm.workshopId
				}).then(res => {
					if (res.data.status === 200) {
						const resData = res.data.res;
						if (resData && resData.length) {
							this.scheduleShiftList = resData[0].scheduleShiftList;
						} else {
							tipsBar(this, 'custom', 'warning', '当前时间未排班，请排班后再操作！');
						}
					}
				});
			}
		},
		onDateChange() {
			this.$set(this.ruleForm, 'scheduleShiftId', null);
			this.$set(this.ruleForm, 'shiftName', null);
			this.$set(this.ruleForm, 'shiftId', null);
			this.$set(this.ruleForm, 'prdReportMachineList', []);
			this.scheduleShiftList = [];
			this.getDateScheduleShiftOptionRequest();
		},
		getHistoryDataRequest() {
			return productionPrdMonthReportHistoryPage({
				selectMaster: false,
				prdReportId: this.ruleForm.prdReportId ? this.ruleForm.prdReportId : this.ruleForm.id
			}).then(res => {
				if (res.data.status === 200) {
					this.historyData = res.data.res;
				}
			});
		},
		async getDependentData() {
			this.showLoading = true;
			this.dataId = this.$route.query.id ? Number(this.$route.query.id) : null;
			this.processList = this.$store.state.user.userProcess.processList;
			if (this.pageType !== 'detail') {
				this.workshopList = this.$store.state.user.userWorkshop.workshopList;
				if (!this.dataId) {
					this.$set(this.ruleForm, 'processId', this.$route.query.processId ? Number(this.$route.query.processId) : this.$store.state.user.userProcess.defaultProcessId);
					this.$set(this.ruleForm, 'workshopId', this.$route.query.workshopId ? Number(this.$route.query.workshopId) : this.$store.state.user.userWorkshop.defaultWorkshopId);
					this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
				}
			}
			if (this.dataId) await this.getDetailRequest();
			await this.getDateScheduleShiftOptionRequest();
			// await this.getHistoryDataRequest();
			this.$nextTick(() => {
				this.$refs.ruleForm.clearValidate();
			});
			this.showLoading = false;
		}
	},
	watch: {
		ruleForm: {
			handler() {
				this.$refs.jkTable.$refs.xTable.updateFooter();
				this.calTotal();
				this.getProductList();
			},
			deep: true
		}
	},
	mounted() {
		_this = this;
	}
};
